package com.wtone.platform.gat.images.gat.job;

import com.wtone.platform.gat.images.gat.config.RedisUtils;
import com.wtone.platform.gat.images.gat.entity.SubscribeDB;
import com.wtone.platform.gat.images.gat.mapper.SubscribeMapper;
import com.wtone.platform.gat.images.gat.model.Subscribe;
import com.wtone.platform.gat.images.gat.utils.BenUtils;
import com.wtone.platform.gat.images.gat.utils.DateUtils;
import com.wtone.platform.gat.images.gat.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

/**
 * @Author: aiLin
 * @Date: 2020/9/28 16:25
 * @desc: 订阅者信息同步
 */
@Slf4j
//@Component
public class SubscriJob {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private SubscribeMapper subscribeMapper;

    /***
     * 每5分钟同步一次
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void command(){
        List<Subscribe> subscribeAlls = redisUtils.getSubscribeAlls();
        log.info("定时同步订阅人列表subscribe:{}",subscribeAlls);
        if(subscribeAlls!=null && subscribeAlls.size()>0){
            for(int i=0;i<subscribeAlls.size();i++){
                try {
                    SubscribeDB subscribeDB = (SubscribeDB)BenUtils.beanTobeanLowerCase(subscribeAlls.get(i), SubscribeDB.class);
                    subscribeDB.setCreateBy("admin");
                    subscribeDB.setRemark(DateUtils.getDate()+"系统同步");
                    subscribeDB.setCreateTime(DateUtils.getNowDate());
                    //根据订阅id 判断是否已经存在
                    List<SubscribeDB> subscribeDBS = subscribeMapper.selectSubscribeObj(subscribeDB);
                    if(subscribeDBS!=null && subscribeDBS.size()>0){
                        for(int j=0;j<subscribeDBS.size();j++){
                            subscribeMapper.deleteSubscribeById(subscribeDBS.get(j).getId(),"");
                        }
                    }
                    if(StringUtils.isEmpty(subscribeDB.getSubscribeid()) ||StringUtils.isEmpty(subscribeDB.getApplicantname()) || StringUtils.isEmpty(subscribeDB.getApplicantorg()) || StringUtils.isEmpty(subscribeDB.getReceiveaddr())){
                        log.info("参数：{}，异常，略过同步",subscribeDB.getSubscribeid());
                    }
                    subscribeMapper.insertSubscribe(subscribeDB);
                } catch (Exception e) {
                    log.error("subscribeDB-Ben,复制异常e:{}",e);
                }
            }
        }
    }
}
